//
//  TrainManageController.m
//  Coach_HaiGeEr
//
//  Created by liuchen on 2018/10/12.
//  Copyright © 2018年 海格尔. All rights reserved.
//

#import "TrainManageController.h"
#import "BXHCalendarView.h"
#import "TrainManageSelectView.h"
#import "NSDate+BXHCalendar.h"
#import "NSDate+BXHCategory.h"
#import "TrainManagementCell.h"
#import "TrainManage_HeaderSection_View.h"

@interface TrainManageController ()<UITableViewDelegate,UITableViewDataSource,TrainManagementCellDelegate,BXHCalendarViewDataSource,BXHCalendarViewDelegate,TrainManageSelectViewDelegate>
@property (nonatomic,strong) TrainManageSelectView *reasonView;
@property (nonatomic,strong) BXHCalendarView *calendarView;
@property (nonatomic,strong) UITableView *trainTableView;
@property (nonatomic,strong) UIButton *btn_in_resonView;
@property (nonatomic,copy) NSArray *dataArr;
@property (nonatomic,copy) NSArray *array_in_reasonCell;
@property (nonatomic,assign) NSInteger subjectType_in_reasonAllCell;
@property (nonatomic,copy) NSString *str_in_reasonAllCell;
@property (nonatomic,copy) NSString *selectDate;
@end

@implementation TrainManageController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[CoachTabBarController shareLZHTabbarController].tabBar setHidden:YES];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createSubView];
}

#pragma mark ==========创建视图==========
- (void)createSubView{
    self.title = @"培训管理";
    self.view.backgroundColor = [UIColor whiteColor];
    [self setNavBack];
    [self.view addSubview:self.trainTableView];
    [self.calendarView goToToday];
    self.selectDate = [[NSDate date] bxh_stringWithFormate:@"yyyy-MM-dd"];
    [self loadDataWithCurrentDate:self.selectDate];
}

#pragma mark ==========加载数据==========
- (void)loadDataWithCurrentDate:(NSString *)currentDate{
    [self showLoading];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic setValue:currentDate forKey:@"currentDate"];
    [[NetworkEngine sharedClient] GETByToken:TRAINMANAGEMENTList data:dic success:^(id responseObject) {
        [self hideHUD];
        if ([[responseObject objectForKey:@"code"] integerValue]==1) {
            if ([[responseObject objectForKey:@"data"] count]!=0) {
                self.dataArr = [responseObject objectForKey:@"data"];
                [self.trainTableView reloadData];
            }
        } else if ([[responseObject objectForKey:@"code"] integerValue]==2) {
            [self toLoginVC];
        } else {[self showMessage:[responseObject objectForKey:@"msg"]];}
    } failure:^(NSString *error) {
        [self hideHUD];
    }];
}

#pragma mark ==========懒加载==========
- (TrainManageSelectView *)reasonView{
    if (!_reasonView) {
        _reasonView = [[TrainManageSelectView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        _reasonView.delegate = self;
    }
    return _reasonView;
}
- (BXHCalendarView *)calendarView{
    if (!_calendarView) {
        _calendarView = [[BXHCalendarView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 190*SCALEUNIT)];
        _calendarView.dataSource = self;
        _calendarView.delegate = self;
    }
    return _calendarView;
}
- (UITableView *)trainTableView{
    
    if (_trainTableView == nil) {
        _trainTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) style:UITableViewStylePlain];
        _trainTableView.tableHeaderView = self.calendarView;
        _trainTableView.tableFooterView = [[UIView alloc]init];
        _trainTableView.backgroundColor = [UIColor colorWithHexString:@"#eeeeee"];
        _trainTableView.delegate = self;
        _trainTableView.dataSource = self;
        _trainTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLineEtched;
        [_trainTableView setSeparatorInset:UIEdgeInsetsMake(0, 30*SCALEUNIT, 0, 30*SCALEUNIT)];
        [_trainTableView setSeparatorColor:[UIColor colorWithHexString:@"#eeeeee"]];
        [_trainTableView registerClass:[TrainManagementCell class] forCellReuseIdentifier:@"TrainManagementCell"];
    }
    return _trainTableView;
}

#pragma mark ==========UITableView代理方法==========
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArr.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [[[self.dataArr objectAtIndex:section] objectForKey:@"schoolTimeList"] count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100*SCALEUNIT;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    TrainManagementCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TrainManagementCell" forIndexPath:indexPath];
    cell.delegate = self;
    if (self.dataArr!=nil) {
        NSMutableArray *temArr = [[NSMutableArray alloc] init];
        [temArr addObject:[[[self.dataArr objectAtIndex:indexPath.section] objectForKey:@"schoolTimeList"] objectAtIndex:indexPath.row]];
        [temArr addObject:[NSNumber numberWithInteger:[[[self.dataArr objectAtIndex:indexPath.section] objectForKey:@"subjectType"]  integerValue]]];
        [temArr addObject:self.selectDate];
        cell.dataArr = (NSArray *)temArr;
    }
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 120*SCALEUNIT;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    TrainManage_HeaderSection_View *headerView = [[TrainManage_HeaderSection_View alloc] initWithTitle:section==0?@"科目二":@"科目三"];
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:[self.dataArr objectAtIndex:section]];
    [dic setValue:self.selectDate forKey:@"selectDate"];
    headerView.dic = dic;
    headerView.cancleBtn.tag = 10000+section;
    [headerView.cancleBtn addTarget:self action:@selector(cancleAll:) forControlEvents:UIControlEventTouchUpInside];
    return headerView;
}

#pragma mark ==========BXHCalendarViewDataSource+BXHCalendarViewDelegate==========
- (void)calendarView:(BXHCalendarView *)calendarView willShowMonthView:(BXHCalendarMonthView *)monthView{
    //self.title = [NSString stringWithFormat:@"%@",[monthView.beaginDate bxh_stringWithFormate:@"yyyy-MM-dd"]];
}

- (void)calendarView:(BXHCalendarView *)calendarView dayViewHaveEvent:(BXHCalendarDayView *)dayView{
    dayView.haveEvent = dayView.date.day % 3 == 0;
}

- (void)calendarView:(BXHCalendarView *)calendarView didSelectDayView:(BXHCalendarDayView *)dayView{
    self.selectDate = [dayView.date bxh_stringWithFormate:@"yyyy-MM-dd"];
    [self loadDataWithCurrentDate:self.selectDate];
}

#pragma mark ==========TrainManagementCellDelegate(取消+恢复)==========
/*
 createDate = "2018-10-15 09:41:43";
 createUserId = 1;
 createUserName = "\U8d85\U7ea7\U7ba1\U7406\U5458";
 dictId = 211627905225064448;
 dictNo = 1007;
 id = 211628190282547200;
 isUse = 1;
 name = "\U4e2a\U4eba\U539f\U56e0";
 orderno = 3;
 updateDate = "2018-10-15 09:41:43";
 updateUserId = 1;
 updateUserName = "\U8d85\U7ea7\U7ba1\U7406\U5458";
 val = 3;
 */
- (void)trainManagementCellDelegateWithMessage:(NSArray *)dataArr WithBtn:(UIButton *)btn{
    self.array_in_reasonCell = dataArr;
    self.btn_in_resonView = btn;
    if ([[[dataArr objectAtIndex:0] objectForKey:@"state"] integerValue]==1) {//取消
        self.subjectType_in_reasonAllCell=0;
        self.str_in_reasonAllCell = [[self.array_in_reasonCell objectAtIndex:0] objectForKey:@"id"];
        [self.view addSubview:self.reasonView];
        [self.reasonView doAnimation];
    } else if ([[[self.array_in_reasonCell objectAtIndex:0] objectForKey:@"state"] integerValue]==2) {//恢复
        NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
        [dic setValue:[NSNumber numberWithInteger:self.btn_in_resonView.selected?2:1] forKey:@"state"];
        [dic setValue:[self.array_in_reasonCell objectAtIndex:1] forKey:@"subjectType"];
        [dic setValue:[NSNumber numberWithLong:0] forKey:@"dictId"];
        [dic setValue:self.selectDate forKey:@"currentDate"];
        [dic setValue:[[self.array_in_reasonCell objectAtIndex:0] objectForKey:@"recordId"] forKey:@"ids"];
        [[NetworkEngine sharedClient] POSTByToken:TRAINMANAGEMENTCANCLERECOVERY data:dic success:^(id responseObject) {
            [self hideHUD];
            if ([[responseObject objectForKey:@"code"] integerValue]==1) {
                [self loadDataWithCurrentDate:self.selectDate];
            } else if ([[responseObject objectForKey:@"code"] integerValue]==2) {
                [self toLoginVC];
            } else {
                [self showMessage:[responseObject objectForKey:@"msg"]];
            }
        } failure:^(NSString *error) {
            [self hideHUD];
        }];
    } else {}
    btn.userInteractionEnabled = YES;
}

#pragma mark ==========TrainManageSelectViewDelegate(确认取消+跳转登录)==========
- (void)trainManageSelectViewDelegateWithReasonId:(NSNumber *)idNum WithState:(BOOL)stateJudge{
    if (stateJudge) {//确认取消
        if (idNum!=[NSNumber numberWithLong:0]) {
            [self.reasonView removeFromSuperview];
            NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
            [dic setValue:[NSNumber numberWithInteger:self.btn_in_resonView.selected?2:1] forKey:@"state"];
            [dic setValue:[NSNumber numberWithInteger:self.subjectType_in_reasonAllCell==0?[[self.array_in_reasonCell objectAtIndex:1] integerValue]:self.subjectType_in_reasonAllCell] forKey:@"subjectType"];
            [dic setValue:idNum forKey:@"dictId"];
            [dic setValue:self.selectDate forKey:@"currentDate"];
            [dic setValue:self.str_in_reasonAllCell forKey:@"ids"];
            [[NetworkEngine sharedClient] POSTByToken:TRAINMANAGEMENTCANCLERECOVERY data:dic success:^(id responseObject) {
                [self hideHUD];
                if ([[responseObject objectForKey:@"code"] integerValue]==1) {
                    [self loadDataWithCurrentDate:self.selectDate];
                } else if ([[responseObject objectForKey:@"code"] integerValue]==2) {
                    [self toLoginVC];
                } else {
                    [self showMessage:[responseObject objectForKey:@"msg"]];
                }
            } failure:^(NSString *error) {
                [self hideHUD];
            }];
        } else {
            [self showMessage:@"请选择取消原因"];
        }
    } else {
        [self.reasonView removeFromSuperview];
    }
}
- (void)trainManageSelectViewDelegateToLoign{
    [self toLoginVC];
}

#pragma mark ==========取消全部+恢复全部==========
- (void)cancleAll:(UIButton *)btn{
    self.btn_in_resonView = btn;
    if (self.btn_in_resonView.selected == NO) {//取消
        self.subjectType_in_reasonAllCell = btn.tag-10000==0?2:3;
        self.str_in_reasonAllCell = [self getIdsWithKey:@"id" WithSection:btn.tag-10000==0?0:1];
        [self.view addSubview:self.reasonView];
        [self.reasonView doAnimation];
    } else {
        NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
        [dic setValue:[NSNumber numberWithInteger:2] forKey:@"state"];
        [dic setValue:[NSNumber numberWithInteger:btn.tag-10000==0?2:3] forKey:@"subjectType"];
        [dic setValue:[NSNumber numberWithLong:0] forKey:@"dictId"];
        [dic setValue:self.selectDate forKey:@"currentDate"];
        [dic setValue:[self getIdsWithKey:@"recordId" WithSection:btn.tag-10000==0?0:1] forKey:@"ids"];
        [[NetworkEngine sharedClient] POSTByToken:TRAINMANAGEMENTCANCLERECOVERY data:dic success:^(id responseObject) {
            [self hideHUD];
            if ([[responseObject objectForKey:@"code"] integerValue]==1) {
                [self loadDataWithCurrentDate:self.selectDate];
            } else if ([[responseObject objectForKey:@"code"] integerValue]==2) {
                [self toLoginVC];
            } else {
                [self showMessage:[responseObject objectForKey:@"msg"]];
            }
        } failure:^(NSString *error) {
            [self hideHUD];
        }];
    }
}

#pragma mark ==========获取全部id==========btn.tag-10000==0?0:1
- (NSString *)getIdsWithKey:(NSString *)key WithSection:(NSInteger)section{
    NSArray *tempArr = [[self.dataArr objectAtIndex:section] objectForKey:@"schoolTimeList"];
    NSString *solution = [[tempArr objectAtIndex:0] objectForKey:key];
    for (int i=1; i<tempArr.count; i++) {
        solution = [NSString stringWithFormat:@"%@,%@",solution,[[tempArr objectAtIndex:i] objectForKey:key]];
    }
    return solution;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
